import { defineStore } from 'pinia'
import Decimal from 'decimal.js'
import { CurrencyItem, ExchangeRate } from '@/types'
import { getCurrencyList, getExchangeRate } from '@/api/wallet.ts'
import { CurrencyEnum, CurrencyFiatEnum } from '@/enums'

export const useCurrencyStore = defineStore('currency', {
	state: () => ({
		exchangeRate: {} as ExchangeRate,
		fiatList: [] as CurrencyItem[],
		cryptoList: [] as CurrencyItem[],
		loading: {
			exchangeRate: false,
			currencyList: false
		}
	}),
	actions: {
		setExchangeRate(data: ExchangeRate) {
			// 接口只有所有货币=>法币的汇率;在这里补充加密币对加密币的汇率
			const currencyKeys = <CurrencyEnum[]>Object.keys(data)
			const USD = CurrencyFiatEnum.USD
			const warnings = <any[]>[]
			currencyKeys.forEach((key) => {
				// 将所有key货币转换为USD，再转换为key的汇率 填充到key对应的对象中
				const key1ToUsd = key === USD ? 1 : data[key][USD]
				currencyKeys.forEach((key2) => {
					if (key !== key2 && !data[key][key2]) {
						const key2ToUsd = key2 === USD ? 1 : data[key2][USD]
						if (key1ToUsd && key2ToUsd) {
							data[key][key2] = Decimal.div(key1ToUsd, key2ToUsd).toFixed(36)
						} else {
							warnings.push({ key, key2, key1ToUsd, key2ToUsd })
						}
					}
				})
			})
			if (warnings.length) {
				console.groupCollapsed('汇率表换算出现异常:')
				warnings.forEach((i) => console.log(i))
				console.groupEnd()
			}
			this.exchangeRate = data
		},
		// 获取所有货币汇率
		async getExchangeRate() {
			try {
				this.loading.exchangeRate = true
				const { data } = await getExchangeRate()
				this.setExchangeRate(data)
			} catch (error) {
				console.error(error)
			} finally {
				this.loading.exchangeRate = false
			}
		},
		// 获取币种(法币/数字货币)列表
		async getCurrencyList() {
			try {
				this.loading.currencyList = true
				const { data } = await getCurrencyList()
				this.fiatList = data.fiat
				this.cryptoList = data.crypto
			} catch (error) {
				console.error(error)
			} finally {
				this.loading.currencyList = false
			}
		}
	}
})
